home *** CD-ROM | disk | FTP | other *** search
/ CU Amiga Super CD-ROM 17 / CU Amiga Magazine's Super CD-ROM 17 (1997)(EMAP Images)(GB)[!][issue 1997-12].iso / CUCD / Sound / MusicIn / common.c < prev    next >
C/C++ Source or Header  |  1997-09-23  |  49KB  |  1,561 lines

  1. /**********************************************************************
  2. Copyright (c) 1991 MPEG/audio software simulation group, All Rights Reserved
  3. common.c
  4. **********************************************************************/
  5. /**********************************************************************
  6.  * MPEG/audio coding/decoding software, work in progress              *
  7.  *   NOT for public distribution until verified and approved by the   *
  8.  *   MPEG/audio committee.  For further information, please contact   *
  9.  *   Davis Pan, 508-493-2241, e-mail: pan@3d.enet.dec.com             *
  10.  *                                                                    *
  11.  * VERSION 4.0                                                        *
  12.  *   changes made since last update:                                  *
  13.  *   date   programmers         comment                               *
  14.  * 2/25/91  Doulas Wong,        start of version 1.0 records          *
  15.  *          Davis Pan                                                 *
  16.  * 5/10/91  W. Joseph Carter    Created this file for all common      *
  17.  *                              functions and global variables.       *
  18.  *                              Ported to Macintosh and Unix.         *
  19.  *                              Added Jean-Georges Fritsch's          *
  20.  *                              "bitstream.c" package.                *
  21.  *                              Added routines to handle AIFF PCM     *
  22.  *                              sound files.                          *
  23.  *                              Added "mem_alloc()" and "mem_free()"  *
  24.  *                              routines for memory allocation        *
  25.  *                              portability.                          *
  26.  *                              Added routines to convert between     *
  27.  *                              Apple SANE extended floating point    *
  28.  *                              format and IEEE double precision      *
  29.  *                              floating point format.  For AIFF.     *
  30.  * 02jul91 dpwe (Aware Inc)     Moved allocation table input here;    *
  31.  *                              Tables read from subdir TABLES_PATH.  *
  32.  *                              Added some debug printout fns (Write*)*
  33.  * 7/10/91 Earle Jennings       replacement of the one float by FLOAT *
  34.  *                              port to MsDos from MacIntosh version  *
  35.  * 8/ 5/91 Jean-Georges Fritsch fixed bug in open_bit_stream_r()      *
  36.  *10/ 1/91 S.I. Sudharsanan,    Ported to IBM AIX platform.           *
  37.  *         Don H. Lee,                                                *
  38.  *         Peter W. Farrett                                           *
  39.  *10/3/91  Don H. Lee           implemented CRC-16 error protection   *
  40.  *                              newly introduced functions are        *
  41.  *                              I_CRC_calc, II_CRC_calc and           *
  42.  *                              update_CRC. Additions and revisions   *
  43.  *                              are marked with dhl for clarity       *
  44.  *10/18/91 Jean-Georges Fritsch fixed bug in update_CRC(),            *
  45.  *                              II_CRC_calc() and I_CRC_calc()        *
  46.  * 2/11/92  W. Joseph Carter    Ported new code to Macintosh.  Most   *
  47.  *                              important fixes involved changing     *
  48.  *                              16-bit ints to long or unsigned in    *
  49.  *                              bit alloc routines for quant of 65535 *
  50.  *                              and passing proper function args.     *
  51.  *                              Removed "Other Joint Stereo" option   *
  52.  *                              and made bitrate be total channel     *
  53.  *                              bitrate, irrespective of the mode.    *
  54.  *                              Fixed many small bugs & reorganized.  *
  55.  * 3/20/92 Jean-Georges Fritsch  fixed bug in start-of-frame search   *
  56.  * 6/15/92 Juan Pineda          added refill_buffer(bs) "n"           *
  57.  *                              initialization                        *
  58.  * 7/08/92 Susanne Ritscher     MS-DOS, MSC6.0 port fixes             *
  59.  * 7/27/92 Mike Li               (re-)Port to MS-DOS                  *
  60.  * 8/19/92 Soren H. Nielsen     Fixed bug in I_CRC_calc and in        *
  61.  *                              II_CRC_calc.  Added function: new_ext *
  62.  *                              for better MS-DOS compatability       *
  63.  * 3/10/93 Kevin Peterson       changed aiff_read_headers to handle   *
  64.  *                              chunks in any order.  now returns     *
  65.  *                              position of sound data in file.       *
  66.  * 3/31/93 Jens Spille          changed IFF_* string compares to use  *
  67.  *                              strcmp()                              *
  68.  * 5/30/93 Masahiro Iwadare     ?? the previous modification does not *
  69.  *                                work. recovered to the original. ?? *
  70.  * 8/27/93 Seymour Shlien,      Fixes in Unix and MSDOS ports,        *
  71.  *         Daniel Lauzon, and                                         *
  72.  *         Bill Truerniet                                             *
  73.  * 12/02/95 Stephane Tavenard   int -> long for return of function    *
  74.  *                              aiff_read_headers, return when sound  *
  75.  *                              chunk is found.                       *
  76.  **********************************************************************/
  77.  
  78. /***********************************************************************
  79. *
  80. *  Global Include Files
  81. *
  82. ***********************************************************************/
  83.  
  84. #include        "common.h"
  85.  
  86. #ifdef  MACINTOSH
  87.  
  88. #include        <SANE.h>
  89. #include        <pascal.h>
  90.  
  91. #endif
  92.  
  93. #include <ctype.h>
  94.  
  95. /***********************************************************************
  96. *
  97. *  Global Variable Definitions
  98. *
  99. ***********************************************************************/
  100.  
  101. char *mode_names[4] = { "stereo", "j-stereo", "dual-ch", "single-ch" };
  102. char *layer_names[3] = { "I", "II", "III" };
  103.  
  104. double  s_freq[4] = {44.1, 48, 32, 0};
  105.  
  106. int     bitrate[3][15] = {
  107.           {0,32,64,96,128,160,192,224,256,288,320,352,384,416,448},
  108.           {0,32,48,56,64,80,96,112,128,160,192,224,256,320,384},
  109.           {0,32,40,48,56,64,80,96,112,128,160,192,224,256,320}
  110.         };
  111.  
  112. double FAR multiple[64] = {
  113. 2.00000000000000, 1.58740105196820, 1.25992104989487,
  114. 1.00000000000000, 0.79370052598410, 0.62996052494744, 0.50000000000000,
  115. 0.39685026299205, 0.31498026247372, 0.25000000000000, 0.19842513149602,
  116. 0.15749013123686, 0.12500000000000, 0.09921256574801, 0.07874506561843,
  117. 0.06250000000000, 0.04960628287401, 0.03937253280921, 0.03125000000000,
  118. 0.02480314143700, 0.01968626640461, 0.01562500000000, 0.01240157071850,
  119. 0.00984313320230, 0.00781250000000, 0.00620078535925, 0.00492156660115,
  120. 0.00390625000000, 0.00310039267963, 0.00246078330058, 0.00195312500000,
  121. 0.00155019633981, 0.00123039165029, 0.00097656250000, 0.00077509816991,
  122. 0.00061519582514, 0.00048828125000, 0.00038754908495, 0.00030759791257,
  123. 0.00024414062500, 0.00019377454248, 0.00015379895629, 0.00012207031250,
  124. 0.00009688727124, 0.00007689947814, 0.00006103515625, 0.00004844363562,
  125. 0.00003844973907, 0.00003051757813, 0.00002422181781, 0.00001922486954,
  126. 0.00001525878906, 0.00001211090890, 0.00000961243477, 0.00000762939453,
  127. 0.00000605545445, 0.00000480621738, 0.00000381469727, 0.00000302772723,
  128. 0.00000240310869, 0.00000190734863, 0.00000151386361, 0.00000120155435,
  129. 1E-20
  130. };
  131.  
  132. /***********************************************************************
  133. *
  134. *  Global Function Definitions
  135. *
  136. ***********************************************************************/
  137.  
  138. /* The system uses a variety of data files.  By opening them via this
  139.    function, we can accommodate various locations. */
  140.  
  141. FILE *OpenTableFile(name)
  142. char *name;
  143. {
  144. char fulname[80];
  145. char *envdir;
  146. FILE *f;
  147.  
  148.      fulname[0] = '\0';
  149.  
  150. #ifdef TABLES_PATH
  151.        strcpy(fulname, TABLES_PATH);   /* default relative path for tables */
  152. #endif /* TABLES_PATH */          /* (includes terminal path seperator */
  153.  
  154. #ifdef UNIX                       /* envir. variables for UNIX only */
  155.        {
  156. #ifndef _DCC                /* ST 09/04/1995 */
  157.         char *getenv();
  158. #endif
  159.         envdir = getenv(MPEGTABENV);   /* check for environment */
  160.         if(envdir != NULL)
  161.             strcpy(fulname, envdir);
  162.         strcat(fulname, PATH_SEPARATOR);  /* add a "/" on the end */
  163.       }
  164. #endif /* UNIX */
  165.  
  166.     strcat(fulname, name);
  167.     if( (f=fopen(fulname,"r"))==NULL ) {
  168.         fprintf(stderr,"OpenTable: could not find %s\n", fulname);
  169.  
  170. #ifdef UNIX
  171.           if(envdir != NULL)
  172.             fprintf(stderr,"Check %s directory '%s'\n",MPEGTABENV, envdir);
  173.           else
  174.             fprintf(stderr,"Check local directory './%s' or setenv %s\n",
  175.                     TABLES_PATH, MPEGTABENV);
  176. #else /* not unix : no environment variables */
  177.  
  178. #ifdef TABLES_PATH
  179.             fprintf(stderr,"Check local directory './%s'\n",TABLES_PATH);
  180. #endif /* TABLES_PATH */
  181.  
  182. #endif /* UNIX */
  183.  
  184.     }
  185.     return f;
  186. }
  187.  
  188. /************************************************************************/
  189. /*                                                                      */
  190. /* Read one of the data files ("alloc_*") specifying the bit allocation */
  191. /* quatization parameters for each subband in layer II encoding         */
  192. /*                                                                      */
  193. /************************************************************************/
  194.  
  195. int read_bit_alloc(table, alloc)        /* read in table, return # subbands */
  196. int table;
  197. al_table *alloc;
  198. {
  199.         unsigned int a, b, c, d, i, j;
  200.         FILE *fp;
  201.         char name[16], t[80];
  202.         int sblim;
  203.  
  204.         strcpy(name, "alloc_0");
  205.  
  206.         switch (table) {
  207.                 case 0 : name[6] = '0';         break;
  208.                 case 1 : name[6] = '1';         break;
  209.                 case 2 : name[6] = '2';         break;
  210.                 case 3 : name[6] = '3';         break;
  211.                 default : name[6] = '0';
  212.         }
  213.  
  214.         if (!(fp = OpenTableFile(name))) {
  215.                 printf("Please check bit allocation table %s\n", name);
  216.                 exit(1);
  217.         }
  218.  
  219.         printf("using bit allocation table %s\n", name);
  220.  
  221.         fgets(t, 80, fp);
  222.         sscanf(t, "%d\n", &sblim);
  223.         while (!feof(fp)) {
  224.                 fgets(t, 80, fp);
  225.                 sscanf(t, "%d %d %d %d %d %d\n", &i, &j, &a, &b, &c, &d);
  226.                         (*alloc)[i][j].steps = a;
  227.                         (*alloc)[i][j].bits  = b;
  228.                         (*alloc)[i][j].group = c;
  229.                         (*alloc)[i][j].quant = d;
  230.         }
  231.         fclose(fp);
  232.         return sblim;
  233. }
  234.  
  235. /**********************************************************************/
  236. /*                                                                    */
  237. /* Using the decoded info the appropriate possible quantization per   */
  238. /* subband table is loaded                                            */
  239. /*                                                                    */
  240. /**********************************************************************/
  241.  
  242. int pick_table(fr_ps)   /* choose table, load if necess, return # sb's */
  243. frame_params *fr_ps;
  244. {
  245.         int table, lay, ws, bsp, br_per_ch, sfrq;
  246.         int sblim = fr_ps->sblimit;     /* return current value if no load */
  247.  
  248.         lay = fr_ps->header->lay - 1;
  249.         bsp = fr_ps->header->bitrate_index;
  250.         br_per_ch = bitrate[lay][bsp] / fr_ps->stereo;
  251.         ws = fr_ps->header->sampling_frequency;
  252.         sfrq = s_freq[ws];
  253.         /* decision rules refer to per-channel bitrates (kbits/sec/chan) */
  254.         if ((sfrq == 48 && br_per_ch >= 56) ||
  255.             (br_per_ch >= 56 && br_per_ch <= 80)) table = 0;
  256.         else if (sfrq != 48 && br_per_ch >= 96) table = 1;
  257.         else if (sfrq != 32 && br_per_ch <= 48) table = 2;
  258.         else table = 3;
  259.         if (fr_ps->tab_num != table) {
  260.            if (fr_ps->tab_num >= 0)
  261.               mem_free((void **)&(fr_ps->alloc));
  262.            fr_ps->alloc = (al_table FAR *) mem_alloc(sizeof(al_table),
  263.                                                          "alloc");
  264.            sblim = read_bit_alloc(fr_ps->tab_num = table, fr_ps->alloc);
  265.         }
  266.         return sblim;
  267. }
  268.  
  269. int js_bound(lay, m_ext)
  270. int lay, m_ext;
  271. {
  272. static int jsb_table[3][4] =  { { 4, 8, 12, 16 }, { 4, 8, 12, 16},
  273.                                 { 0, 4, 8, 16} };  /* lay+m_e -> jsbound */
  274.  
  275.     if(lay<1 || lay >3 || m_ext<0 || m_ext>3) {
  276.         fprintf(stderr, "js_bound bad layer/modext (%d/%d)\n", lay, m_ext);
  277.         exit(1);
  278.     }
  279.     return(jsb_table[lay-1][m_ext]);
  280. }
  281.  
  282. void hdr_to_frps(fr_ps) /* interpret data in hdr str to fields in fr_ps */
  283. frame_params *fr_ps;
  284. {
  285. layer *hdr = fr_ps->header;     /* (or pass in as arg?) */
  286.  
  287.     fr_ps->actual_mode = hdr->mode;
  288.     fr_ps->stereo = (hdr->mode == MPG_MD_MONO) ? 1 : 2;
  289.     if (hdr->lay == 2)          fr_ps->sblimit = pick_table(fr_ps);
  290.     else                        fr_ps->sblimit = SBLIMIT;
  291.     if(hdr->mode == MPG_MD_JOINT_STEREO)
  292.         fr_ps->jsbound = js_bound(hdr->lay, hdr->mode_ext);
  293.     else
  294.         fr_ps->jsbound = fr_ps->sblimit;
  295.     /* alloc, tab_num set in pick_table */
  296. }
  297.  
  298. void WriteHdr(fr_ps, s)
  299. frame_params *fr_ps;
  300. FILE *s;
  301. {
  302. layer *info = fr_ps->header;
  303.  
  304.    fprintf(s, "HDR:  s=FFF, id=%X, l=%X, ep=%X, br=%X, sf=%X, pd=%X, ",
  305.            info->version, info->lay, !info->error_protection,
  306.            info->bitrate_index, info->sampling_frequency, info->padding);
  307.    fprintf(s, "pr=%X, m=%X, js=%X, c=%X, o=%X, e=%X\n",
  308.            info->extension, info->mode, info->mode_ext,
  309.            info->copyright, info->original, info->emphasis);
  310.    fprintf(s, "layer=%s, tot bitrate=%d, sfrq=%.1f, mode=%s, ",
  311.            layer_names[info->lay-1], bitrate[info->lay-1][info->bitrate_index],
  312.            s_freq[info->sampling_frequency], mode_names[info->mode]);
  313.    fprintf(s, "sblim=%d, jsbd=%d, ch=%d\n",
  314.            fr_ps->sblimit, fr_ps->jsbound, fr_ps->stereo);
  315.    fflush(s);
  316. }
  317.  
  318. void WriteBitAlloc(bit_alloc, f_p, s)
  319. unsigned int bit_alloc[2][SBLIMIT];
  320. frame_params *f_p;
  321. FILE *s;
  322. {
  323. int i,j;
  324. int st = f_p->stereo;
  325. int sbl = f_p->sblimit;
  326. int jsb = f_p->jsbound;
  327.  
  328.     fprintf(s, "BITA ");
  329.     for(i=0; i<sbl; ++i) {
  330.         if(i == jsb) fprintf(s,"-");
  331.         for(j=0; j<st; ++j)
  332.             fprintf(s, "%1x", bit_alloc[j][i]);
  333.     }
  334.     fprintf(s, "\n");   fflush(s);
  335. }
  336.  
  337. void WriteScale(bit_alloc, scfsi, scalar, fr_ps, s)
  338. unsigned int bit_alloc[2][SBLIMIT], scfsi[2][SBLIMIT], scalar[2][3][SBLIMIT];
  339. frame_params *fr_ps;
  340. FILE *s;
  341. {
  342. int stereo  = fr_ps->stereo;
  343. int sblimit = fr_ps->sblimit;
  344. int lay     = fr_ps->header->lay;
  345. int i,j,k;
  346.  
  347.         if(lay == 2) {
  348.             fprintf(s, "SFSI ");
  349.             for (i=0;i<sblimit;i++) for (k=0;k<stereo;k++)
  350.                 if (bit_alloc[k][i])  fprintf(s,"%d",scfsi[k][i]);
  351.             fprintf(s, "\nSCFs ");
  352.             for (k=0;k<stereo;k++) {
  353.                 for (i=0;i<sblimit;i++)
  354.                     if (bit_alloc[k][i])
  355.                         switch (scfsi[k][i]) {
  356.                           case 0: for (j=0;j<3;j++)
  357.                                   fprintf(s,"%2d%c",scalar[k][j][i],
  358.                                           (j==2)?';':'-');
  359.                                   break;
  360.                           case 1:
  361.                           case 3: fprintf(s,"%2d-",scalar[k][0][i]);
  362.                                   fprintf(s,"%2d;",scalar[k][2][i]);
  363.                                   break;
  364.                           case 2: fprintf(s,"%2d;",scalar[k][0][i]);
  365.                         }
  366.                 fprintf(s, "\n");
  367.             }
  368.         }
  369.         else{   /* lay == 1 */
  370.             fprintf(s, "SCFs ");
  371.             for (i=0;i<sblimit;i++) for (k=0;k<stereo;k++)
  372.                 if (bit_alloc[k][i])  fprintf(s,"%2d;",scalar[k][0][i]);
  373.             fprintf(s, "\n");
  374.         }
  375. }
  376.  
  377. void WriteSamples(ch, sample, bit_alloc, fr_ps, s)
  378. int ch;
  379. unsigned int FAR sample[SBLIMIT];
  380. unsigned int bit_alloc[SBLIMIT];
  381. frame_params *fr_ps;
  382. FILE *s;
  383. {
  384. int i;
  385. int stereo = fr_ps->stereo;
  386. int sblimit = fr_ps->sblimit;
  387.  
  388.         fprintf(s, "SMPL ");
  389.         for (i=0;i<sblimit;i++)
  390.                 if ( bit_alloc[i] != 0)
  391.                     fprintf(s, "%d:", sample[i]);
  392.         if(ch==(stereo-1) )     fprintf(s, "\n");
  393.         else                    fprintf(s, "\t");
  394. }
  395.  
  396. int NumericQ(s) /* see if a string lookd like a numeric argument */
  397. char *s;
  398. {
  399. char    c;
  400.  
  401.     while( (c = *s++)!='\0' && isspace((int)c)) /* strip leading ws */
  402.         ;
  403.     if( c == '+' || c == '-' )
  404.         c = *s++;               /* perhaps skip leading + or - */
  405.     return isdigit((int)c);
  406. }
  407.  
  408. int BitrateIndex(layr, bRate)   /* convert bitrate in kbps to index */
  409. int     layr;           /* 1 or 2 */
  410. int     bRate;          /* legal rates from 32 to 448 */
  411. {
  412. int     index = 0;
  413. int     found = 0;
  414.  
  415.     while(!found && index<15)   {
  416.         if(bitrate[layr-1][index] == bRate)
  417.             found = 1;
  418.         else
  419.             ++index;
  420.     }
  421.     if(found)
  422.         return(index);
  423.     else {
  424.         fprintf(stderr, "BitrateIndex: %d (layer %d) is not a legal bitrate\n",
  425.                 bRate, layr);
  426.         return(-1);     /* Error! */
  427.     }
  428. }
  429.  
  430. int SmpFrqIndex(sRate)  /* convert samp frq in Hz to index */
  431. long sRate;             /* legal rates 32000, 44100, 48000 */
  432. {
  433.     if(sRate == 44100L)
  434.         return(0);
  435.     else if(sRate == 48000L)
  436.         return(1);
  437.     else if(sRate == 32000L)
  438.         return(2);
  439.     else {
  440.         fprintf(stderr, "SmpFrqIndex: %ld is not a legal sample rate\n", sRate);
  441.         return(-1);      /* Error! */
  442.     }
  443. }
  444.  
  445. /*******************************************************************************
  446. *
  447. *  Allocate number of bytes of memory equal to "block".
  448. *
  449. *******************************************************************************/
  450.  
  451. void  FAR *mem_alloc(block, item)
  452. unsigned long   block;
  453. char            *item;
  454. {
  455.  
  456.     void    *ptr;
  457.  
  458. #if 0         /* ST 10/04/1995 */
  459.    fprintf( stderr, "memalloc(%ld,%s)\n",block, item );
  460. #endif
  461.  
  462. #ifdef  MACINTOSH
  463.     ptr = NewPtr(block);
  464. #endif
  465.  
  466. #ifdef MSC60
  467.     /*ptr = (void FAR *) _fmalloc((unsigned int)block);*/ /* far memory, 92-07-08 sr */
  468.     ptr = (void FAR *) malloc((unsigned int)block); /* far memory, 93-08-24 ss */
  469. #endif
  470.  
  471. #if ! defined (MACINTOSH) && ! defined (MSC60)
  472.     ptr = (void FAR *) malloc(block);
  473. #endif
  474.  
  475.     if (ptr != NULL){
  476. #ifdef  MSC60
  477.         _fmemset(ptr, 0, (unsigned int)block); /* far memory, 92-07-08 sr */
  478. #else
  479.         memset(ptr, 0, block);
  480. #endif
  481.     }
  482.     else{
  483.         printf("Unable to allocate %s\n", item);
  484.         exit(0);
  485.     }
  486.     return(ptr);
  487. }
  488.  
  489.  
  490. /****************************************************************************
  491. *
  492. *  Free memory pointed to by "*ptr_addr".
  493. *
  494. *****************************************************************************/
  495.  
  496. void    mem_free(ptr_addr)
  497. void    **ptr_addr;
  498. {
  499.  
  500.     if (*ptr_addr != NULL){
  501. #ifdef  MACINTOSH
  502.         DisposPtr(*ptr_addr);
  503. #else
  504.         free(*ptr_addr);
  505. #endif
  506.         *ptr_addr = NULL;
  507.     }
  508.  
  509. }
  510.  
  511. /*******************************************************************************
  512. *
  513. *  Check block of memory all equal to a single byte, else return FALSE
  514. *
  515. *******************************************************************************/
  516.  
  517. int memcheck(array, test, num)
  518. char *array;
  519. int test;       /* but only tested as a char (bottom 8 bits) */
  520. int num;
  521. {
  522.  int i=0;
  523.  
  524.    while (array[i] == test && i<num) i++;
  525.    if (i==num) return TRUE;
  526.    else return FALSE;
  527. }
  528.  
  529. /****************************************************************************
  530. *
  531. *  Routines to convert between the Apple SANE extended floating point format
  532. *  and the IEEE double precision floating point format.  These routines are
  533. *  called from within the Audio Interchange File Format (AIFF) routines.
  534. *
  535. *****************************************************************************/
  536.  
  537. /*
  538. *** Apple's 80-bit SANE extended has the following format:
  539.  
  540.  1       15      1            63
  541. +-+-------------+-+-----------------------------+
  542. |s|       e     |i|            f                |
  543. +-+-------------+-+-----------------------------+
  544.   msb        lsb   msb                       lsb
  545.  
  546. The value v of the number is determined by these fields as follows:
  547. If 0 <= e < 32767,              then v = (-1)^s * 2^(e-16383) * (i.f).
  548. If e == 32767 and f == 0,       then v = (-1)^s * (infinity), regardless of i.
  549. If e == 32767 and f != 0,       then v is a NaN, regardless of i.
  550.  
  551. *** IEEE Draft Standard 754 Double Precision has the following format:
  552.  
  553. MSB
  554. +-+---------+-----------------------------+
  555. |1| 11 Bits |           52 Bits           |
  556. +-+---------+-----------------------------+
  557.  ^     ^                ^
  558.  |     |                |
  559.  Sign  Exponent         Mantissa
  560. */
  561.  
  562. /*****************************************************************************
  563. *
  564. *  double_to_extended()
  565. *
  566. *  Purpose:     Convert from IEEE double precision format to SANE extended
  567. *               format.
  568. *
  569. *  Passed:      Pointer to the double precision number and a pointer to what
  570. *               will hold the Apple SANE extended format value.
  571. *
  572. *  Outputs:     The SANE extended format pointer will be filled with the
  573. *               converted value.
  574. *
  575. *  Returned:    Nothing.
  576. *
  577. *****************************************************************************/
  578.  
  579. void    double_to_extended(pd, ps)
  580. double  *pd;
  581. char    ps[10];
  582. {
  583.  
  584. #ifdef  MACINTOSH
  585.  
  586.         x96tox80(pd, (extended *) ps);
  587.  
  588. #else
  589.  
  590. register unsigned long  top2bits;
  591.  
  592. register unsigned short *ps2;
  593. register IEEE_DBL       *p_dbl;
  594. register SANE_EXT       *p_ext;
  595.  
  596.    p_dbl = (IEEE_DBL *) pd;
  597.    p_ext = (SANE_EXT *) ps;
  598.    top2bits = p_dbl->hi & 0xc0000000;
  599.    p_ext->l1 = ((p_dbl->hi >> 4) & 0x3ff0000) | top2bits;
  600.    p_ext->l1 |= ((p_dbl->hi >> 5) & 0x7fff) | 0x8000;
  601.    p_ext->l2 = (p_dbl->hi << 27) & 0xf8000000;
  602.    p_ext->l2 |= ((p_dbl->lo >> 5) & 0x07ffffff);
  603.    ps2 = (unsigned short *) & (p_dbl->lo);
  604.    ps2++;
  605.    p_ext->s1 = (*ps2 << 11) & 0xf800;
  606.  
  607. #endif
  608.  
  609. }
  610.  
  611. /*****************************************************************************
  612. *
  613. *  extended_to_double()
  614. *
  615. *  Purpose:     Convert from SANE extended format to IEEE double precision
  616. *               format.
  617. *
  618. *  Passed:      Pointer to the Apple SANE extended format value and a pointer
  619. *               to what will hold the the IEEE double precision number.
  620. *
  621. *  Outputs:     The IEEE double precision format pointer will be filled with
  622. *               the converted value.
  623. *
  624. *  Returned:    Nothing.
  625. *
  626. *****************************************************************************/
  627.  
  628. void    extended_to_double(ps, pd)
  629. char    ps[10];
  630. double  *pd;
  631. {
  632.  
  633. #ifdef  MACINTOSH
  634.  
  635.    x80tox96((extended *) ps, pd);
  636.  
  637. #else
  638.  
  639. register unsigned long  top2bits;
  640.  
  641. register IEEE_DBL       *p_dbl;
  642. register SANE_EXT       *p_ext;
  643.  
  644.    p_dbl = (IEEE_DBL *) pd;
  645.    p_ext = (SANE_EXT *) ps;
  646.    top2bits = p_ext->l1 & 0xc0000000;
  647.    p_dbl->hi = ((p_ext->l1 << 4) & 0x3ff00000) | top2bits;
  648.    p_dbl->hi |= (p_ext->l1 << 5) & 0xffff0;
  649.    p_dbl->hi |= (p_ext->l2 >> 27) & 0x1f;
  650.    p_dbl->lo = (p_ext->l2 << 5) & 0xffffffe0;
  651.    p_dbl->lo |= (unsigned long) ((p_ext->s1 >> 11) & 0x1f);
  652.  
  653. #endif
  654.  
  655. }
  656.  
  657.  
  658. /****  for debugging
  659. showchar(str)
  660. char str[4];
  661. {
  662. int i;
  663. for (i=0;i<4;i++) printf("%c",str[i]);
  664. printf("\n");
  665. }
  666. ****/
  667.  
  668. /*****************************************************************************
  669. *
  670. *  Read Audio Interchange File Format (AIFF) headers.
  671. *
  672. *****************************************************************************/
  673.  
  674. long            aiff_read_headers(file_ptr, aiff_ptr)
  675. FILE            *file_ptr;
  676. IFF_AIFF        *aiff_ptr;
  677. {
  678.  
  679. register char   i;
  680. register long   seek_offset;
  681. register long   sound_position = -1;
  682.  
  683. char            temp_sampleRate[10];
  684.  
  685. ChunkHeader     Header;
  686. Chunk           FormChunk;
  687. CommonChunk     CommChunk;
  688. SoundDataChunk  SndDChunk;
  689.  
  690.    if (fseek(file_ptr, 0, SEEK_SET) != 0)
  691.       return(-1);
  692.  
  693.    if (fread(&FormChunk, sizeof(Chunk), 1, file_ptr) != 1)
  694.       return(-1);
  695.  
  696. #ifdef IFF_LONG
  697.    if (*(unsigned long *) FormChunk.ckID != IFF_ID_FORM ||
  698.        *(unsigned long *) FormChunk.formType != IFF_ID_AIFF)
  699.       return(-1);
  700. #else
  701.  
  702.    if (strncmp(FormChunk.ckID,IFF_ID_FORM,4) ||
  703.        strncmp(FormChunk.formType,IFF_ID_AIFF,4))
  704.       return(-1);
  705. #endif
  706.  
  707.    /*
  708.     * chunks need not be in any particular order
  709.     */
  710.  
  711.    while (fread(&Header, sizeof(ChunkHeader), 1, file_ptr) == 1) {
  712.  
  713. #ifdef IFF_LONG
  714.       if (*(unsigned long *)Header.ckID == IFF_ID_COMM) {
  715.  
  716. #else
  717.       if (strncmp(Header.ckID,IFF_ID_COMM,4) == 0) {
  718. #endif
  719.  
  720.          /*
  721.           * read comm chunk
  722.           */
  723.          if (fread(&CommChunk.numChannels, sizeof(short), 1, file_ptr) != 1)
  724.             return(-1);
  725.  
  726.          if (fread(&CommChunk.numSampleFrames, sizeof(unsigned long), 1,
  727.                    file_ptr) != 1)
  728.             return(-1);
  729.  
  730.          if (fread(&CommChunk.sampleSize, sizeof(short), 1, file_ptr) != 1)
  731.             return(-1);
  732.  
  733.          if (fread(CommChunk.sampleRate, sizeof(char[10]), 1, file_ptr) != 1)
  734.             return(-1);
  735.  
  736.          for (i = 0; i < sizeof(char[10]); i++)
  737.             temp_sampleRate[i] = CommChunk.sampleRate[i];
  738.  
  739.          extended_to_double(temp_sampleRate, &aiff_ptr->sampleRate);
  740.  
  741.          aiff_ptr->numChannels = CommChunk.numChannels;
  742.          aiff_ptr->numSampleFrames = CommChunk.numSampleFrames;
  743.          aiff_ptr->sampleSize = CommChunk.sampleSize;
  744.  
  745. #ifdef IFF_LONG
  746.       } else if (*(unsigned long *)Header.ckID == IFF_ID_SSND) {
  747. #else
  748.       } else if (strncmp(Header.ckID,IFF_ID_SSND,4) == 0) {
  749. #endif
  750.          /*
  751.           * read ssnd chunk
  752.           */
  753.          if (fread(&SndDChunk.offset, sizeof(long), 1, file_ptr) != 1)
  754.             return(-1);
  755.  
  756.          if (fread(&SndDChunk.blockSize, sizeof(long), 1, file_ptr) != 1)
  757.             return(-1);
  758.  
  759.          aiff_ptr->blkAlgn.offset = SndDChunk.offset;
  760.          aiff_ptr->blkAlgn.blockSize = SndDChunk.blockSize;
  761.          aiff_ptr->sampleType = *(unsigned long *)Header.ckID;
  762.  
  763.          /*
  764.           * record position of sound data
  765.           */
  766.  
  767.          sound_position = ftell(file_ptr);
  768.  
  769.          return sound_position; /* ST: 12/02/1995 */
  770.  
  771.          /*
  772.           * skip over sound data to look at remaining chunks
  773.           */
  774. /*
  775.          seek_offset = Header.ckSize - sizeof(SoundDataChunk) +
  776.             sizeof(ChunkHeader);
  777.  
  778.          if (fseek(file_ptr, seek_offset, SEEK_CUR) != 0)
  779.             return(-1);
  780. */
  781.       } else {
  782.  
  783.          /*
  784.           * skip unknown chunk
  785.           */
  786.  
  787.          seek_offset = Header.ckSize;
  788.  
  789.          if (fseek(file_ptr, seek_offset, SEEK_CUR) != 0)
  790.             return(-1);
  791.  
  792.       }
  793.  
  794.    }
  795.  
  796.    return(sound_position);
  797.  
  798. }
  799.  
  800. /*****************************************************************************
  801. *
  802. *  Seek past some Audio Interchange File Format (AIFF) headers to sound data.
  803. *
  804. *****************************************************************************/
  805.  
  806. int   aiff_seek_to_sound_data(file_ptr)
  807. FILE  *file_ptr;
  808. {
  809.  
  810.    if (fseek(file_ptr, sizeof(Chunk) + sizeof(SoundDataChunk), SEEK_SET) != 0)
  811.       return(-1);
  812.  
  813.    return(0);
  814.  
  815. }
  816.  
  817. /*******************************************************************************
  818. *
  819. *  Write Audio Interchange File Format (AIFF) headers.
  820. *
  821. *******************************************************************************/
  822.  
  823. int             aiff_write_headers(file_ptr, aiff_ptr)
  824. FILE            *file_ptr;
  825. IFF_AIFF        *aiff_ptr;
  826. {
  827.  
  828. register char   i;
  829. register long   seek_offset;
  830.  
  831. char            temp_sampleRate[10];
  832.  
  833. Chunk           FormChunk;
  834. CommonChunk     CommChunk;
  835. SoundDataChunk  SndDChunk;
  836.  
  837. #ifdef IFF_LONG
  838.    *(unsigned long *) FormChunk.ckID     = IFF_ID_FORM;
  839.    *(unsigned long *) FormChunk.formType = IFF_ID_AIFF;
  840.    *(unsigned long *) CommChunk.ckID     = IFF_ID_COMM;
  841. #else
  842.    strncpy(FormChunk.ckID,IFF_ID_FORM,4);
  843.    strncpy(FormChunk.formType,IFF_ID_AIFF,4);
  844.    strncpy(CommChunk.ckID,IFF_ID_COMM,4);
  845. #endif
  846.  
  847.    double_to_extended(&aiff_ptr->sampleRate, temp_sampleRate);
  848.  
  849.    for (i = 0; i < sizeof(char[10]); i++)
  850.       CommChunk.sampleRate[i] = temp_sampleRate[i];
  851.  
  852.    CommChunk.numChannels             = aiff_ptr->numChannels;
  853.    CommChunk.numSampleFrames         = aiff_ptr->numSampleFrames;
  854.    CommChunk.sampleSize              = aiff_ptr->sampleSize;
  855.    SndDChunk.offset                  = aiff_ptr->blkAlgn.offset;
  856.    SndDChunk.blockSize               = aiff_ptr->blkAlgn.blockSize;
  857.    *(unsigned long *) SndDChunk.ckID = aiff_ptr->sampleType;
  858.  
  859.    CommChunk.ckSize = sizeof(CommChunk.numChannels) +
  860.       sizeof(CommChunk.numSampleFrames) + sizeof(CommChunk.sampleSize) +
  861.       sizeof(CommChunk.sampleRate);
  862.  
  863.    SndDChunk.ckSize = sizeof(SoundDataChunk) - sizeof(ChunkHeader) +
  864.       (CommChunk.sampleSize + BITS_IN_A_BYTE - 1) / BITS_IN_A_BYTE *
  865.       CommChunk.numChannels * CommChunk.numSampleFrames;
  866.  
  867.    FormChunk.ckSize = sizeof(Chunk) + SndDChunk.ckSize + sizeof(ChunkHeader) +
  868.       CommChunk.ckSize;
  869.  
  870.    if (fseek(file_ptr, 0, SEEK_SET) != 0)
  871.       return(-1);
  872.  
  873.    if (fwrite(&FormChunk, sizeof(Chunk), 1, file_ptr) != 1)
  874.       return(-1);
  875.  
  876.    if (fwrite(&SndDChunk, sizeof(SoundDataChunk), 1, file_ptr) != 1)
  877.       return(-1);
  878.  
  879.    seek_offset = SndDChunk.ckSize - sizeof(SoundDataChunk) +
  880.       sizeof(ChunkHeader);
  881.  
  882.    if (fseek(file_ptr, seek_offset, SEEK_CUR) != 0)
  883.       return(-1);
  884.  
  885.    if (fwrite(CommChunk.ckID, sizeof(ID), 1, file_ptr) != 1)
  886.       return(-1);
  887.  
  888.    if (fwrite(&CommChunk.ckSize, sizeof(long), 1, file_ptr) != 1)
  889.       return(-1);
  890.  
  891.    if (fwrite(&CommChunk.numChannels, sizeof(short), 1, file_ptr) != 1)
  892.       return(-1);
  893.  
  894.    if (fwrite(&CommChunk.numSampleFrames, sizeof(unsigned long), 1,
  895.               file_ptr) != 1)
  896.       return(-1);
  897.  
  898.    if (fwrite(&CommChunk.sampleSize, sizeof(short), 1, file_ptr) != 1)
  899.       return(-1);
  900.  
  901.    if (fwrite(CommChunk.sampleRate, sizeof(char[10]), 1, file_ptr) != 1)
  902.       return(-1);
  903.  
  904.    return(0);
  905.  
  906. }
  907.  
  908. /*****************************************************************************
  909. *
  910. *  bit_stream.c package
  911. *  Author:  Jean-Georges Fritsch, C-Cube Microsystems
  912. *
  913. *****************************************************************************/
  914.  
  915. /********************************************************************
  916.   This package provides functions to write (exclusive or read)
  917.   information from (exclusive or to) the bit stream.
  918.  
  919.   If the bit stream is opened in read mode only the get functions are
  920.   available. If the bit stream is opened in write mode only the put
  921.   functions are available.
  922. ********************************************************************/
  923.  
  924. /*open_bit_stream_w(); open the device to write the bit stream into it    */
  925. /*open_bit_stream_r(); open the device to read the bit stream from it     */
  926. /*close_bit_stream();  close the device containing the bit stream         */
  927. /*alloc_buffer();      open and initialize the buffer;                    */
  928. /*desalloc_buffer();   empty and close the buffer                         */
  929. /*back_track_buffer();     goes back N bits in the buffer                 */
  930. /*unsigned int get1bit();  read 1 bit from the bit stream                 */
  931. /*unsigned long getbits(); read N bits from the bit stream                */
  932. /*unsigned long byte_ali_getbits();   read the next byte aligned N bits from*/
  933. /*                                    the bit stream                        */
  934. /*unsigned long look_ahead(); grep the next N bits in the bit stream without*/
  935. /*                            changing the buffer pointer                   */
  936. /*put1bit(); write 1 bit from the bit stream  */
  937. /*put1bit(); write 1 bit from the bit stream  */
  938. /*putbits(); write N bits from the bit stream */
  939. /*byte_ali_putbits(); write byte aligned the next N bits into the bit stream*/
  940. /*unsigned long sstell(); return the current bit stream length (in bits)    */
  941. /*int end_bs(); return 1 if the end of bit stream reached otherwise 0       */
  942. /*int seek_sync(); return 1 if a sync word was found in the bit stream      */
  943. /*                 otherwise returns 0                                      */
  944.  
  945. /* refill the buffer from the input device when the buffer becomes empty    */
  946. int refill_buffer(bs)
  947. Bit_stream_struc *bs;   /* bit stream structure */
  948. {
  949.    register int i=bs->buf_size-2-bs->buf_byte_idx;
  950.    register unsigned long n=1;
  951.    register int index=0;
  952.    char val[2];
  953.  
  954.    while ((i>=0) && (!bs->eob)) {
  955.  
  956.       if (bs->format == BINARY) {
  957. /*         n = fread(&bs->buf[i--], sizeof(unsigned char), 1, bs->pt); */
  958.          index = getc( bs->pt );
  959.          bs->buf[i--] = (unsigned char)index;
  960.          if( index == EOF ) n = 0;
  961.       }
  962.       else {
  963.          while((index < 2) && n) {
  964.             n = fread(&val[index], sizeof(char), 1, bs->pt);
  965.             switch (val[index]) {
  966.                   case 0x30:
  967.                   case 0x31:
  968.                   case 0x32:
  969.                   case 0x33:
  970.                   case 0x34:
  971.                   case 0x35:
  972.                   case 0x36:
  973.                   case 0x37:
  974.                   case 0x38:
  975.                   case 0x39:
  976.                   case 0x41:
  977.                   case 0x42:
  978.                   case 0x43:
  979.                   case 0x44:
  980.                   case 0x45:
  981.                   case 0x46:
  982.                   index++;
  983.                   break;
  984.                   default: break;
  985.             }
  986.          }
  987.  
  988.          if (val[0] <= 0x39)   bs->buf[i] = (val[0] - 0x30) << 4;
  989.                  else  bs->buf[i] = (val[0] - 0x37) << 4;
  990.          if (val[1] <= 0x39)   bs->buf[i--] |= (val[1] - 0x30);
  991.                  else  bs->buf[i--] |= (val[1] - 0x37);
  992.          index = 0;
  993.       }
  994.  
  995.       if (!n) {
  996.          bs->eob= i+1;
  997.       }
  998.  
  999.     }
  1000. }
  1001.  
  1002. static char *he = "0123456789ABCDEF";
  1003.  
  1004. /* empty the buffer to the output device when the buffer becomes full */
  1005. void empty_buffer(bs, minimum)
  1006. Bit_stream_struc *bs;   /* bit stream structure */
  1007. int minimum;            /* end of the buffer to empty */
  1008. {
  1009.    register int i;
  1010.  
  1011. #if BS_FORMAT == BINARY
  1012.    for (i=bs->buf_size-1;i>=minimum;i--)
  1013.       fwrite(&bs->buf[i], sizeof(unsigned char), 1, bs->pt);
  1014. #else
  1015.    for (i=bs->buf_size-1;i>=minimum;i--) {
  1016.        char val[2];
  1017.        val[0] = he[((bs->buf[i] >> 4) & 0x0F)];
  1018.        val[1] = he[(bs->buf[i] & 0x0F)];
  1019.        fwrite(val, sizeof(char), 2, bs->pt);
  1020.    }
  1021. #endif
  1022.  
  1023.    for (i=minimum-1; i>=0; i--)
  1024.        bs->buf[bs->buf_size - minimum + i] = bs->buf[i];
  1025.  
  1026.    bs->buf_byte_idx = bs->buf_size -1 - minimum;
  1027.    bs->buf_bit_idx = 8;
  1028. }
  1029.  
  1030. /* open the device to write the bit stream into it */
  1031. void open_bit_stream_w(bs, bs_filenam, size)
  1032. Bit_stream_struc *bs;   /* bit stream structure */
  1033. char *bs_filenam;       /* name of the bit stream file */
  1034. int size;               /* size of the buffer */
  1035. {
  1036.    if ((bs->pt = fopen(bs_filenam, "wb")) == NULL) {
  1037.       printf("Could not create \"%s\".\n", bs_filenam);
  1038.       exit(1);
  1039.    }
  1040.    alloc_buffer(bs, size);
  1041.    bs->buf_byte_idx = size-1;
  1042.    bs->buf_bit_idx=8;
  1043.    bs->totbit=0;
  1044.    bs->mode = WRITE_MODE;
  1045.    bs->eob = FALSE;
  1046.    bs->eobs = FALSE;
  1047. }
  1048.  
  1049. /* open the device to read the bit stream from it */
  1050. void open_bit_stream_r(bs, bs_filenam, size)
  1051. Bit_stream_struc *bs;   /* bit stream structure */
  1052. char *bs_filenam;       /* name of the bit stream file */
  1053. int size;               /* size of the buffer */
  1054. {
  1055.    register unsigned long n;
  1056.    register unsigned char flag = 1;
  1057.    unsigned char val;
  1058.  
  1059.    if ((bs->pt = fopen(bs_filenam, "rb")) == NULL) {
  1060.       printf("Could not find \"%s\".\n", bs_filenam);
  1061.       exit(1);
  1062.    }
  1063.  
  1064.    do {
  1065.      n = fread(&val, sizeof(unsigned char), 1, bs->pt);
  1066.      switch (val) {
  1067.       case 0x30:
  1068.       case 0x31:
  1069.       case 0x32:
  1070.       case 0x33:
  1071.       case 0x34:
  1072.       case 0x35:
  1073.       case 0x36:
  1074.       case 0x37:
  1075.       case 0x38:
  1076.       case 0x39:
  1077.       case 0x41:
  1078.       case 0x42:
  1079.       case 0x43:
  1080.       case 0x44:
  1081.       case 0x45:
  1082.       case 0x46:
  1083.       case 0xa:  /* \n */
  1084.       case 0xd:  /* cr */
  1085.       case 0x1a:  /* sub */
  1086.           break;
  1087.  
  1088.       default: /* detection of an binary character */
  1089.           flag--;
  1090.           break;
  1091.      }
  1092.  
  1093.    } while (flag & n);
  1094.  
  1095.    if (flag) {
  1096.       printf ("the bit stream file %s is an ASCII file\n", bs_filenam);
  1097.       bs->format = ASCII;
  1098.    }
  1099.    else {
  1100.       bs->format = BINARY;
  1101.       printf ("the bit stream file %s is a BINARY file\n", bs_filenam);
  1102.    }
  1103.  
  1104.    fclose(bs->pt);
  1105.  
  1106.    if ((bs->pt = fopen(bs_filenam, "rb")) == NULL) {
  1107.       printf("Could not find \"%s\".\n", bs_filenam);
  1108.       exit(1);
  1109.    }
  1110.  
  1111.    alloc_buffer(bs, size);
  1112.    bs->buf_byte_idx=0;
  1113.    bs->buf_bit_idx=0;
  1114.    bs->totbit=0;
  1115.    bs->mode = READ_MODE;
  1116.    bs->eob = FALSE;
  1117.    bs->eobs = FALSE;
  1118. }
  1119.  
  1120. /*close the device containing the bit stream after a read process*/
  1121. void close_bit_stream_r(bs)
  1122. Bit_stream_struc *bs;   /* bit stream structure */
  1123. {
  1124.    fclose(bs->pt);
  1125.    desalloc_buffer(bs);
  1126. }
  1127.  
  1128. /*close the device containing the bit stream after a write process*/
  1129. void close_bit_stream_w(bs)
  1130. Bit_stream_struc *bs;   /* bit stream structure */
  1131. {
  1132.    empty_buffer(bs, bs->buf_byte_idx);
  1133.    fclose(bs->pt);
  1134.    desalloc_buffer(bs);
  1135. }
  1136.  
  1137. /*open and initialize the buffer; */
  1138. void alloc_buffer(bs, size)
  1139. Bit_stream_struc *bs;   /* bit stream structure */
  1140. int size;
  1141. {
  1142.    bs->buf = (unsigned char FAR *) mem_alloc(size*sizeof(unsigned
  1143.               char), "buffer");
  1144.    bs->buf_size = size;
  1145. }
  1146.  
  1147. /*empty and close the buffer */
  1148. void desalloc_buffer(bs)
  1149. Bit_stream_struc *bs;   /* bit stream structure */
  1150. {
  1151.    free(bs->buf);
  1152. }
  1153.  
  1154. int putmask[9]={0x0, 0x1, 0x3, 0x7, 0xf, 0x1f, 0x3f, 0x7f, 0xff};
  1155. int clearmask[9]={0xff, 0xfe, 0xfc, 0xf8, 0xf0, 0xe0, 0xc0, 0x80, 0x0};
  1156.  
  1157. void back_track_buffer(bs, N) /* goes back N bits in the buffer */
  1158. Bit_stream_struc *bs;   /* bit stream structure */
  1159. int N;
  1160. {
  1161.    int tmp = N - (N/8)*8;
  1162.    register int i;
  1163.  
  1164.    bs->totbit -= N;
  1165.    for (i=bs->buf_byte_idx;i< bs->buf_byte_idx+N/8-1;i++) bs->buf[i] = 0;
  1166.    bs->buf_byte_idx += N/8;
  1167.    if ( (tmp + bs->buf_bit_idx) <= 8) {
  1168.       bs->buf_bit_idx += tmp;
  1169.    }
  1170.    else {
  1171.       bs->buf_byte_idx ++;
  1172.       bs->buf_bit_idx += (tmp - 8);
  1173.    }
  1174.    bs->buf[bs->buf_byte_idx] &= clearmask[bs->buf_bit_idx];
  1175. }
  1176.  
  1177. int mask[8]={0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80};
  1178.  
  1179. /*read 1 bit from the bit stream */
  1180. unsigned int get1bit(bs)
  1181. Bit_stream_struc *bs;   /* bit stream structure */
  1182. {
  1183.    unsigned int bit;
  1184.    register int i;
  1185.  
  1186.    bs->totbit++;
  1187.  
  1188.    if (!bs->buf_bit_idx) {
  1189.         bs->buf_bit_idx = 8;
  1190.         bs->buf_byte_idx--;
  1191.         if ((bs->buf_byte_idx < MINIMUM) || (bs->buf_byte_idx < bs->eob)) {
  1192.              if (bs->eob)
  1193.                 bs->eobs = TRUE;
  1194.              else {
  1195.                 for (i=bs->buf_byte_idx; i>=0;i--)
  1196.                   bs->buf[bs->buf_size-1-bs->buf_byte_idx+i] = bs->buf[i];
  1197.                 refill_buffer(bs);
  1198.                 bs->buf_byte_idx = bs->buf_size-1;
  1199.              }
  1200.         }
  1201.    }
  1202.    bit = bs->buf[bs->buf_byte_idx]&mask[bs->buf_bit_idx-1];
  1203.    bit = bit >> (bs->buf_bit_idx-1);
  1204.    bs->buf_bit_idx--;
  1205.    return(bit);
  1206. }
  1207.  
  1208. /*write 1 bit from the bit stream */
  1209. void put1bit(bs, bit)
  1210. Bit_stream_struc *bs;   /* bit stream structure */
  1211. int bit;                /* bit to write into the buffer */
  1212. {
  1213.    bs->totbit++;
  1214.  
  1215.    bs->buf[bs->buf_byte_idx] |= (bit&0x1) << (bs->buf_bit_idx-1);
  1216.    bs->buf_bit_idx--;
  1217.    if (!bs->buf_bit_idx) {
  1218.        bs->buf_bit_idx = 8;
  1219.        bs->buf_byte_idx--;
  1220.        if (bs->buf_byte_idx < 0)
  1221.           empty_buffer(bs, MINIMUM);
  1222.        bs->buf[bs->buf_byte_idx] = 0;
  1223.    }
  1224. }
  1225.  
  1226. /*look ahead for the next N bits from the bit stream */
  1227. unsigned long look_ahead(bs, N)
  1228. Bit_stream_struc *bs;   /* bit stream structure */
  1229. int N;                  /* number of bits to read from the bit stream */
  1230. {
  1231.  unsigned long val=0;
  1232.  register int j = N;
  1233.  register int k, tmp;
  1234.  register int bit_idx = bs->buf_bit_idx;
  1235.  register int byte_idx = bs->buf_byte_idx;
  1236.  
  1237.  if (N > MAX_LENGTH)
  1238.     printf("Cannot read or write more than %d bits at a time.\n", MAX_LENGTH);
  1239.  
  1240.  while (j > 0) {
  1241.     if (!bit_idx) {
  1242.         bit_idx = 8;
  1243.         byte_idx--;
  1244.     }
  1245.     k = MIN (j, bit_idx);
  1246.     tmp = bs->buf[byte_idx]&putmask[bit_idx];
  1247.     tmp = tmp >> (bit_idx-k);
  1248.     val |= tmp << (j-k);
  1249.     bit_idx -= k;
  1250.     j -= k;
  1251.  }
  1252.  return(val);
  1253. }
  1254.  
  1255. /*read N bit from the bit stream */
  1256. unsigned long getbits(bs, N)
  1257. Bit_stream_struc *bs;   /* bit stream structure */
  1258. int N;                  /* number of bits to read from the bit stream */
  1259. {
  1260.  unsigned long val=0;
  1261.  register int i;
  1262.  register int j = N;
  1263.  register int k, tmp;
  1264.  
  1265.  if (N > MAX_LENGTH)
  1266.     printf("Cannot read or write more than %d bits at a time.\n", MAX_LENGTH);
  1267.  
  1268.  bs->totbit += N;
  1269.  while (j > 0) {
  1270.    if (!bs->buf_bit_idx) {
  1271.         bs->buf_bit_idx = 8;
  1272.         bs->buf_byte_idx--;
  1273.         if ((bs->buf_byte_idx < MINIMUM) || (bs->buf_byte_idx < bs->eob)) {
  1274.              if (bs->eob)
  1275.                 bs->eobs = TRUE;
  1276.              else {
  1277.                 for (i=bs->buf_byte_idx; i>=0;i--)
  1278.                    bs->buf[bs->buf_size-1-bs->buf_byte_idx+i] = bs->buf[i];
  1279.                 refill_buffer(bs);
  1280.                 bs->buf_byte_idx = bs->buf_size-1;
  1281.              }
  1282.         }
  1283.    }
  1284.    k = MIN (j, bs->buf_bit_idx);
  1285.    tmp = bs->buf[bs->buf_byte_idx]&putmask[bs->buf_bit_idx];
  1286.    tmp = tmp >> (bs->buf_bit_idx-k);
  1287.    val |= tmp << (j-k);
  1288.    bs->buf_bit_idx -= k;
  1289.    j -= k;
  1290.  }
  1291.  return(val);
  1292. }
  1293.  
  1294. /*write N bits into the bit stream */
  1295. void putbits(bs, val, N)
  1296. Bit_stream_struc *bs;   /* bit stream structure */
  1297. unsigned int val;       /* val to write into the buffer */
  1298. int N;                  /* number of bits of val */
  1299. {
  1300.  register int j = N;
  1301.  register int k, tmp;
  1302.  
  1303.  if (N > MAX_LENGTH)
  1304.     printf("Cannot read or write more than %d bits at a time.\n", MAX_LENGTH);
  1305.  
  1306.  bs->totbit += N;
  1307.  while (j > 0) {
  1308.    k = MIN(j, bs->buf_bit_idx);
  1309.    tmp = val >> (j-k);
  1310.    bs->buf[bs->buf_byte_idx] |= (tmp&putmask[k]) << (bs->buf_bit_idx-k);
  1311.    bs->buf_bit_idx -= k;
  1312.    if (!bs->buf_bit_idx) {
  1313.        bs->buf_bit_idx = 8;
  1314.        bs->buf_byte_idx--;
  1315.        if (bs->buf_byte_idx < 0)
  1316.           empty_buffer(bs, MINIMUM);
  1317.        bs->buf[bs->buf_byte_idx] = 0;
  1318.    }
  1319.    j -= k;
  1320.  }
  1321. }
  1322.  
  1323. /*write N bits byte aligned into the bit stream */
  1324. void byte_ali_putbits(bs, val, N)
  1325. Bit_stream_struc *bs;   /* bit stream structure */
  1326. unsigned int val;       /* val to write into the buffer */
  1327. int N;                  /* number of bits of val */
  1328. {
  1329.  unsigned long aligning;
  1330. #ifndef _DCC               /* ST 09/04/1995 */
  1331.  unsigned long sstell();
  1332. #endif
  1333.  
  1334.  if (N > MAX_LENGTH)
  1335.     printf("Cannot read or write more than %d bits at a time.\n", MAX_LENGTH);
  1336.  aligning = sstell(bs)%8;
  1337.  if (aligning)
  1338.      putbits(bs, (unsigned int)0, (int)(8-aligning));
  1339.  
  1340.  putbits(bs, val, N);
  1341. }
  1342.  
  1343. /*read the next bute aligned N bits from the bit stream */
  1344. unsigned long byte_ali_getbits(bs, N)
  1345. Bit_stream_struc *bs;   /* bit stream structure */
  1346. int N;                  /* number of bits of val */
  1347. {
  1348.  unsigned long aligning;
  1349. #ifndef _DCC            /* ST 09/04/1995 */
  1350.  unsigned long sstell();
  1351. #endif
  1352.  
  1353.  if (N > MAX_LENGTH)
  1354.     printf("Cannot read or write more than %d bits at a time.\n", MAX_LENGTH);
  1355.  aligning = sstell(bs)%8;
  1356.  if (aligning)
  1357.     getbits(bs, (int)(8-aligning));
  1358.  
  1359.  return(getbits(bs, N));
  1360. }
  1361.  
  1362. /*return the current bit stream length (in bits)*/
  1363. unsigned long sstell(bs)
  1364. Bit_stream_struc *bs;   /* bit stream structure */
  1365. {
  1366.   return(bs->totbit);
  1367. }
  1368.  
  1369. /*return the status of the bit stream*/
  1370. /* returns 1 if end of bit stream was reached */
  1371. /* returns 0 if end of bit stream was not reached */
  1372. int end_bs(bs)
  1373. Bit_stream_struc *bs;   /* bit stream structure */
  1374. {
  1375.   return(bs->eobs);
  1376. }
  1377.  
  1378. /*this function seeks for a byte aligned sync word in the bit stream and
  1379.   places the bit stream pointer right after the sync.
  1380.   This function returns 1 if the sync was found otherwise it returns 0  */
  1381. int seek_sync(bs, sync, N)
  1382. Bit_stream_struc *bs;   /* bit stream structure */
  1383. long sync;      /* sync word maximum 32 bits */
  1384. int N;          /* sync word length */
  1385. {
  1386. #ifndef _DCC      /* ST 09/04/1995 */
  1387.  double pow();
  1388. #endif
  1389.  unsigned long aligning, stell();
  1390.  unsigned long val;
  1391.  long maxi = (int)pow(2.0, (FLOAT)N) - 1;
  1392.  
  1393.  aligning = sstell(bs)%ALIGNING;
  1394.  if (aligning)
  1395.     getbits(bs, (int)(ALIGNING-aligning));
  1396.  
  1397.   val = getbits(bs, N);
  1398.   while (((val&maxi) != sync) && (!end_bs(bs))) {
  1399.         val <<= ALIGNING;
  1400.         val |= getbits(bs, ALIGNING);
  1401.   }
  1402.  
  1403.  if (end_bs(bs)) return(0);
  1404.  else return(1);
  1405. }
  1406. /*****************************************************************************
  1407. *
  1408. *  End of bit_stream.c package
  1409. *
  1410. *****************************************************************************/
  1411.  
  1412. /*****************************************************************************
  1413. *
  1414. *  CRC error protection package
  1415. *
  1416. *****************************************************************************/
  1417.  
  1418. void I_CRC_calc(fr_ps, bit_alloc, crc)
  1419. frame_params *fr_ps;
  1420. unsigned int bit_alloc[2][SBLIMIT];
  1421. unsigned int *crc;
  1422. {
  1423.         int i, k;
  1424.         layer *info = fr_ps->header;
  1425.         int stereo  = fr_ps->stereo;
  1426.         int jsbound = fr_ps->jsbound;
  1427.  
  1428.         *crc = 0xffff; /* changed from '0' 92-08-11 shn */
  1429.         update_CRC(info->bitrate_index, 4, crc);
  1430.         update_CRC(info->sampling_frequency, 2, crc);
  1431.         update_CRC(info->padding, 1, crc);
  1432.         update_CRC(info->extension, 1, crc);
  1433.         update_CRC(info->mode, 2, crc);
  1434.         update_CRC(info->mode_ext, 2, crc);
  1435.         update_CRC(info->copyright, 1, crc);
  1436.         update_CRC(info->original, 1, crc);
  1437.         update_CRC(info->emphasis, 2, crc);
  1438.  
  1439.         for (i=0;i<SBLIMIT;i++)
  1440.                 for (k=0;k<((i<jsbound)?stereo:1);k++)
  1441.                         update_CRC(bit_alloc[k][i], 4, crc);
  1442. }
  1443.  
  1444. void II_CRC_calc(fr_ps, bit_alloc, scfsi, crc)
  1445. frame_params *fr_ps;
  1446. unsigned int bit_alloc[2][SBLIMIT], scfsi[2][SBLIMIT];
  1447. unsigned int *crc;
  1448. {
  1449.         int i, k;
  1450.         layer *info = fr_ps->header;
  1451.         int stereo  = fr_ps->stereo;
  1452.         int sblimit = fr_ps->sblimit;
  1453.         int jsbound = fr_ps->jsbound;
  1454.         al_table *alloc = fr_ps->alloc;
  1455.  
  1456.         *crc = 0xffff; /* changed from '0' 92-08-11 shn */
  1457.         update_CRC(info->bitrate_index, 4, crc);
  1458.         update_CRC(info->sampling_frequency, 2, crc);
  1459.         update_CRC(info->padding, 1, crc);
  1460.         update_CRC(info->extension, 1, crc);
  1461.         update_CRC(info->mode, 2, crc);
  1462.         update_CRC(info->mode_ext, 2, crc);
  1463.         update_CRC(info->copyright, 1, crc);
  1464.         update_CRC(info->original, 1, crc);
  1465.         update_CRC(info->emphasis, 2, crc);
  1466.  
  1467.         for (i=0;i<sblimit;i++)
  1468.                 for (k=0;k<((i<jsbound)?stereo:1);k++)
  1469.                         update_CRC(bit_alloc[k][i], (*alloc)[i][0].bits, crc);
  1470.  
  1471.         for (i=0;i<sblimit;i++)
  1472.                 for (k=0;k<stereo;k++)
  1473.                         if (bit_alloc[k][i])
  1474.                                 update_CRC(scfsi[k][i], 2, crc);
  1475. }
  1476.  
  1477. void update_CRC(data, length, crc)
  1478. unsigned int data, length, *crc;
  1479. {
  1480.         unsigned int  masking, carry;
  1481.  
  1482.         masking = 1 << length;
  1483.  
  1484.         while((masking >>= 1)){
  1485.                 carry = *crc & 0x8000;
  1486.                 *crc <<= 1;
  1487.                 if (!carry ^ !(data & masking))
  1488.                         *crc ^= CRC16_POLYNOMIAL;
  1489.         }
  1490.         *crc &= 0xffff;
  1491. }
  1492.  
  1493. /*****************************************************************************
  1494. *
  1495. *  End of CRC error protection package
  1496. *
  1497. *****************************************************************************/
  1498.  
  1499. #ifdef  MACINTOSH
  1500. /*****************************************************************************
  1501. *
  1502. *  Set Macintosh file attributes.
  1503. *
  1504. *****************************************************************************/
  1505.  
  1506. void    set_mac_file_attr(fileName, vRefNum, creator, fileType)
  1507. char    fileName[MAX_NAME_SIZE];
  1508. short   vRefNum;
  1509. OsType  creator;
  1510. OsType  fileType;
  1511. {
  1512.  
  1513. short   theFile;
  1514. char    pascal_fileName[MAX_NAME_SIZE];
  1515. FInfo   fndrInfo;
  1516.  
  1517.         CtoPstr(strcpy(pascal_fileName, fileName));
  1518.  
  1519.         FSOpen(pascal_fileName, vRefNum, &theFile);
  1520.         GetFInfo(pascal_fileName, vRefNum, &fndrInfo);
  1521.         fndrInfo.fdCreator = creator;
  1522.         fndrInfo.fdType = fileType;
  1523.         SetFInfo(pascal_fileName, vRefNum, &fndrInfo);
  1524.         FSClose(theFile);
  1525.  
  1526. }
  1527. #endif
  1528.  
  1529.  
  1530. #ifdef  MS_DOS
  1531. /* ------------------------------------------------------------------------
  1532. new_ext.
  1533. Puts a new extension name on a file name <filename>.
  1534. Removes the last extension name, if any.
  1535. 92-08-19 shn
  1536. ------------------------------------------------------------------------ */
  1537. char *new_ext(char *filename, char *extname)
  1538. {
  1539.   int found, dotpos;
  1540.   char newname[80];
  1541.  
  1542.   /* First, strip the extension */
  1543.   dotpos=strlen(filename); found=0;
  1544.   do
  1545.   {
  1546.     switch (filename[dotpos])
  1547.     {
  1548.       case '.' : found=1; break;
  1549.       case '\\':                  /* used by MS-DOS */
  1550.       case '/' :                  /* used by UNIX */
  1551.       case ':' : found=-1; break; /* used by MS-DOS in drive designation */
  1552.       default  : dotpos--; if (dotpos<0) found=-1; break;
  1553.     }
  1554.   } while (found==0);
  1555.   if (found==-1) strcpy(newname,filename);
  1556.   if (found== 1) strncpy(newname,filename,dotpos); newname[dotpos]='\0';
  1557.   strcat(newname,extname);
  1558.   return(newname);
  1559. }
  1560. #endif
  1561.